package com.nbcio.cd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nbcio.cd.domain.CdFile;
import com.nbcio.cd.domain.CdFolder;
import com.nbcio.cd.domain.CdUserStorage;
import com.nbcio.cd.mapper.CdFileMapper;
import com.nbcio.cd.mapper.CdFolderMapper;
import com.nbcio.cd.mapper.CdUserStorageMapper;
import com.nbcio.cd.service.ICdUserStorageService;
import com.nbcio.common.satoken.utils.LoginHelper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 云网盘用户存储统计Service业务层处理
 *
 * @author nbacheng
 * @date 2024-01-01
 */
@Service
@RequiredArgsConstructor
public class CdUserStorageServiceImpl extends ServiceImpl<CdUserStorageMapper, CdUserStorage> implements ICdUserStorageService {

    private final CdUserStorageMapper cdUserStorageMapper;
    private final CdFileMapper cdFileMapper;
    private final CdFolderMapper cdFolderMapper;

    @Override
    public CdUserStorage getUserStorage(Long userId) {
        LambdaQueryWrapper<CdUserStorage> lqw = new LambdaQueryWrapper<CdUserStorage>();
        lqw.eq(CdUserStorage::getUserId, userId);
        lqw.eq(CdUserStorage::getDelFlag, "0");
        
        CdUserStorage userStorage = cdUserStorageMapper.selectOne(lqw);
        
        // 如果没有存储统计记录，返回默认值（不自动创建，由管理员分配）
        if (userStorage == null) {
            userStorage = new CdUserStorage();
            userStorage.setUserId(userId);
            userStorage.setTotalSize(0L); // 默认0，需要管理员分配
            userStorage.setUsedSize(0L);
            userStorage.setFileCount(0);
            userStorage.setFolderCount(0);
            userStorage.setStatus("0");
        }
        
        return userStorage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserStorage(Long userId, Long sizeChange, Integer fileCountChange, Integer folderCountChange) {
        CdUserStorage userStorage = getUserStorage(userId);
        
        if (userStorage == null) {
            // 如果不存在，先初始化
            initUserStorage(userId);
            userStorage = getUserStorage(userId);
        }
        
        if (userStorage != null) {
            userStorage.setUsedSize(userStorage.getUsedSize() + sizeChange);
            userStorage.setFileCount(userStorage.getFileCount() + fileCountChange);
            userStorage.setFolderCount(userStorage.getFolderCount() + folderCountChange);
            userStorage.setUpdateBy(LoginHelper.getUserId());
            userStorage.setUpdateTime(new Date());
            
            cdUserStorageMapper.updateById(userStorage);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void initUserStorage(Long userId) {
        // 检查是否已存在
        CdUserStorage existingStorage = getUserStorage(userId);
        if (existingStorage != null) {
            return;
        }
        
        // 创建新的存储统计
        CdUserStorage userStorage = new CdUserStorage();
        userStorage.setUserId(userId);
        userStorage.setTotalSize(5L * 1024 * 1024 * 1024); // 默认5GB
        userStorage.setUsedSize(0L);
        userStorage.setFileCount(0);
        userStorage.setFolderCount(1); // 包含根文件夹
        userStorage.setStatus("0");
        userStorage.setCreateBy(userId);
        userStorage.setCreateTime(new Date());
        
        cdUserStorageMapper.insert(userStorage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CdUserStorage syncUserStorage(Long userId) {
        // 获取或创建用户存储统计
        CdUserStorage userStorage = getUserStorage(userId);
        if (userStorage == null) {
            initUserStorage(userId);
            userStorage = getUserStorage(userId);
        }
        
        // 计算实际使用的存储空间
        LambdaQueryWrapper<CdFile> fileWrapper = new LambdaQueryWrapper<CdFile>();
        fileWrapper.eq(CdFile::getCreateBy, userId);
        fileWrapper.eq(CdFile::getDelFlag, "0");
        
        long totalSize = cdFileMapper.selectList(fileWrapper).stream()
            .mapToLong(CdFile::getFileSize)
            .sum();
        
        // 计算文件数量
        int fileCount = Math.toIntExact(cdFileMapper.selectCount(fileWrapper));
        
        // 计算文件夹数量
        LambdaQueryWrapper<CdFolder> folderWrapper = new LambdaQueryWrapper<CdFolder>();
        folderWrapper.eq(CdFolder::getOwnerId, userId);
        folderWrapper.eq(CdFolder::getDelFlag, "0");
        int folderCount = Math.toIntExact(cdFolderMapper.selectCount(folderWrapper));
        
        // 更新存储统计
        userStorage.setUsedSize(totalSize);
        userStorage.setFileCount(fileCount);
        userStorage.setFolderCount(folderCount);
        userStorage.setUpdateBy(userId);
        userStorage.setUpdateTime(new Date());
        
        cdUserStorageMapper.updateById(userStorage);
        
        return userStorage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setUserStorageQuota(Long userId, Long totalSize) {
        // 获取或创建用户存储统计
        CdUserStorage userStorage = getUserStorage(userId);
        if (userStorage == null) {
            initUserStorage(userId);
            userStorage = getUserStorage(userId);
        }
        
        if (userStorage != null) {
            // 更新总存储空间
            userStorage.setTotalSize(totalSize);
            userStorage.setUpdateBy(LoginHelper.getUserId());
            userStorage.setUpdateTime(new Date());
            
            cdUserStorageMapper.updateById(userStorage);
        }
    }
}
